﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Framework.Project.Web.Mvc.Html;
using System.Web.SessionState;
using System.Threading;
using System.Web.Script.Serialization;
using Framework.Project.Adapter.Native;
using Framework.Project.Info.Security;
using Framework.Project.Info;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using Framework.Project.Web.Mvc;
using Framework.Utils;
using AdvTicket.Common.Library;

namespace AdvTicket.Admin.Web.Server
{
  public class CAdminLoginPage : CLoginPage
  {
    public static string StrAuthorizeMsg = "You are not authorized to access Admin Panel !";

    public CAdminLoginPage()
      : base()
    {
      IsRequiredJquery = false;
      LoginPageLogo = CFrameworkResourceModule.GetUrl("AdvTicket_Admin_Login.png");
    }

    public override string VersionInfo
    {
      get { return CAdvTicketCommon.VersionInfo; }
    }

    public override void Dispose()
    {
      base.Dispose();
    }

    [CWebMethod]
    new public static string Authenticate(string UserName, string Password, bool RememberMe)
    {
      string returningScript = hideErrorMsgScript + changeErrorMsgScript + "('" + "" + "');" + hideLoadingPaneScript;

      // Admin Panele girme hakkı olup olmadığı kontrol ediliyor...
      var TableInfo_Users = ProjectAdapter.DesignerProjectInfo.Tables[CProjectInfoHelper.UsersTableName];

      var Fields = new CFieldInfoList(TableInfo_Users.Indexes.UniqueIndexedFields.Fields);
      Fields.AddIfNotContains(TableInfo_Users["ProjectNo"]);
      Fields.AddIfNotContains(TableInfo_Users["UserNo"]);
      Fields.AddIfNotContains(TableInfo_Users["UserName"]);

      var Filter = new CConditionInfo(TableInfo_Users.Fields,
        new CConditionItemInfo(TableInfo_Users["ProjectNo"], ProjectAdapter.ProjectInfo.No),
        new CConditionItemInfo(TableInfo_Users["UserName"], UserName)
        );

      var Table = ProjectAdapter.LoadDataObject(TableInfo_Users, Fields, Filter);
      if (Table.DefaultView.Count > 0)
      {
        //Table.Rows[0]
        var TableInfo_UsersAdminRole = ProjectAdapter.ProjectInfo.Tables["UsersAdminRole"];

        var Fields_AdminRole = new CFieldInfoList(TableInfo_UsersAdminRole.Indexes.UniqueIndexedFields.Fields);
        Fields_AdminRole.AddIfNotContains(TableInfo_UsersAdminRole["ProjectNo"]);
        Fields_AdminRole.AddIfNotContains(TableInfo_UsersAdminRole["UserNo"]);
        Fields_AdminRole.AddIfNotContains(TableInfo_UsersAdminRole["AccessAdminPanel"]);

        var Filter_AdminRole = new CConditionInfo(TableInfo_UsersAdminRole.Fields,
          new CConditionItemInfo(TableInfo_UsersAdminRole["ProjectNo"], ProjectAdapter.ProjectInfo.No),
          new CConditionItemInfo(TableInfo_UsersAdminRole["UserNo"], Table.DefaultView[0]["UserNo"])
          );

        var Table_AdminRole = ProjectAdapter.LoadDataObject(TableInfo_UsersAdminRole, Fields_AdminRole, Filter_AdminRole);

        string resultMsg = GetLabelFromDB(LoginSectionName, StrAuthorizeMsg);
        string tempScript = changeErrorMsgScript + "('" + resultMsg + "');" + showErrorMsgScript;

        if (Table_AdminRole.DefaultView.Count == 0)
        {
          // Admin Panele girmeye hakkı yok ise...
          return returningScript + tempScript;
        }
        else
        {
          bool isAccessAdminPanel = Convert.ToBoolean(Table_AdminRole.Rows[0]["AccessAdminPanel"]);

          if (!isAccessAdminPanel)
            return returningScript + tempScript;
        }
      }

      //ProjectAdapter.UserInfo.HasRole
      var Result = ProjectAdapter.Authenticate_v2(UserName, Password, false, true);

      // Authentication sağlanır ise,
      if (Result.Result == CAuthenticationResult.PasswordExpired || Result.Result == CAuthenticationResult.MustChangePassword)
      {
        Application.Authenticate();
        string resultMsg = GetLabelFromDB(LoginSectionName, strAuthenticationMustChangePassword);
        string resultWarning = GetLabelFromDB(LoginSectionName, strAuthenticationWarning);

        if (RememberMe)
          Application.SessionVariables.RememberMe = true;

        string ChangePasswordScript = DocumentLocationScript.Replace("{0}", GetUrlWithVirtualPath(Application.ApplicationVariables.ChangePasswordPageUrlName));
        return hideLoadingPaneScript + PageMethods_showDialogScript(resultWarning, resultMsg, PageMethodDialogType.warning, 3, ChangePasswordScript);
      }
      else if (Result.Result == CAuthenticationResult.Successfull)
      {
        Application.Authenticate();

        if (RememberMe)
        {
          Application.SessionVariables.RememberMe = true;
          SetUserInfoCookie(UserName, Password);
        }

        string MainPageScript = DocumentLocationScript.Replace("{0}", GetUrlWithVirtualPath(Application.ApplicationVariables.MainPageUrlName));

        // Ana Sayfaya yönlendirme için script eklendi.
        returningScript = returningScript + MainPageScript;
      }
      else
      {
        // Eğer Authentication sağlanmamış ise, Cookie siliniyor.
        if (UserInfoCookieExists())
        {
          Application.SessionVariables.RememberMe = false;
          RemoveUserInfoCookie();
        }

        string msgResultStr = CLoginPage.GetAuthenticationResultText(Result.Result);
        // Eğer Şifre Yanlış Girilmiş ve Expire olmaya doğru gidiyor ise...
        if (Result.Result == CAuthenticationResult.WrongPassword)
          msgResultStr = string.Format(msgResultStr, Result.WrongPasswordEntryCount.ToString(), Result.AllowedWrongPasswordEntryCount.ToString());

        returningScript = returningScript + changeErrorMsgScript + "('" + msgResultStr + "');" + showErrorMsgScript;
      }

      return returningScript;

      // Aşağıdaki kodlar test için kullanıldı...
      // PageMethods_showConfirmDialogScript("Confirm", "Evet Yada Hayır", 0, Helper.GetAlertScript("Evete Tıkladınız...", '\''));
      // PageMethods_showDialogScript("Test", "test", PageMethodDialogType.warning, 0); 
    }



  }

}